package org.acme.oauth2.reactive;

import io.quarkus.vertx.web.Route;
import io.quarkus.vertx.web.RoutingExchange;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;

import javax.enterprise.context.ApplicationScoped;
import java.util.Base64;

/**
 * @author LiJian
 * @date 2021/6/8 11:08
 */
@ApplicationScoped
public class ReactiveRescource extends AbstractVerticle {
    // neither path nor regex is set - match a path derived from the method name
    @Route(methods = HttpMethod.GET)
    //
    void hello(RoutingContext rc) {  //3
        Vertx vertx = Vertx.vertx();
        WebClientOptions options = new WebClientOptions();
        options.setDefaultHost("http://192.168.99.77:9998");
        WebClient webClient = WebClient.create(vertx, options);
        String url = "http://192.168.99.77:9998/oauth/authorize?client_id=tdfuivue&response_type=code&scope=user_info&state=&redirect_uri=http%3A%2F%2Flocalhost%3A9527%2Fssologin";

        var ref = new Object() {
            String xsrfCooike = "";
        };
        webClient.getAbs(url).send(ar -> {
            if (ar.succeeded()) {
                HttpResponse<Buffer> response = ar.result();
                ref.xsrfCooike = response.cookies().toString();
                System.out.println(response.cookies().toString());
            } else {
                System.out.println("发送请求失败：" + ar.cause().getMessage());
            }
            String oauthKey = Base64.getEncoder().encodeToString(("tdfuivue" + ":" + "tdfuivue").getBytes());
            System.out.println(oauthKey);
        });
        HttpRequest<Buffer> request = webClient.request(HttpMethod.GET, "/1.0/orders");
        request.send(asyncResult -> {
            if (asyncResult.succeeded()) {
                HttpResponse<Buffer> response = asyncResult.result();
                System.out.println("status code:" + response.statusCode());
            } else {
                System.err.println("error:" + asyncResult.cause().getMessage());
            }
        });
        rc.response().end("hello");
    }

    @Route(path = "/world")
    String helloWorld() { //4
        return "Hello world!";
    }

    @Route(path = "/greetings", methods = HttpMethod.GET)
    void greetings(RoutingExchange ex) { //5
        ex.ok("hello " + ex.getParam("name").orElse("world"));
    }
}
